package com.ruoyi.app;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.app.dto.*;
import com.ruoyi.app.param.OrderParam;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.order.domain.*;
import com.ruoyi.order.service.*;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.service.IProductService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/app/mine")
public class AppMineController extends BaseController {


    @Autowired
    private IOrderService orderService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IUserCollectionService userCollectionService;

    @Autowired
    private IProductService productService;

    @Autowired
    private IDeliveryService deliveryService;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private IBasketService basketService;

    @Autowired
    private IUserAddrService userAddrService;

    @Autowired
    private IAreaService areaService;

    /**
     * 服务对象
     */
    @Resource
    private OrderItemService orderItemService;


    /**
     * 新增数据
     *
     * @param orderItem 实体
     * @return 新增结果
     */
    @PostMapping("orderConfirm")
    public ResponseEntity<OrderItem> add(@RequestBody OrderItem orderItem, HttpServletRequest request) {
        LoginUser user = tokenService.getLoginUser(request);
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        orderItem.setOrderNumber(uuid);
        orderItem.setRecTime(new Date());
        orderItem.setMemberId(user.getUserId());
        if (orderItem.getCommSts() == null) {
            orderItem.setCommSts(0);
        }

        orderItemService.insert(orderItem);
        return ResponseEntity.ok(orderItem);
    }

    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('order:order:query')")
    @GetMapping(value = "orderCount")
    public AjaxResult mineOrderCount(HttpServletRequest request) {
        LoginUser user = tokenService.getLoginUser(request);
        OrderCount orderCount = orderService.selectOrderByMemberId(user.getUserId());
        return success(orderCount);
    }

    /**
     * 查询收藏列表
     */
    @PreAuthorize("@ss.hasPermi('order:collection:list')")
    @GetMapping("/collectionCount")
    public AjaxResult list(HttpServletRequest request) {
        LoginUser user = tokenService.getLoginUser(request);
        UserCollection userCollection = new UserCollection();
        userCollection.setUserId(String.valueOf(user.getUserId()));
        List<UserCollection> list = userCollectionService.selectUserCollectionList(userCollection);
        return success(list.size());
    }

    /**
     * 查询收藏列表
     */
    @PreAuthorize("@ss.hasPermi('order:collection:list')")
    @GetMapping("/userCollectionList")
    public AjaxResult getCollectionProd(HttpServletRequest request) {
        LoginUser user = tokenService.getLoginUser(request);
        UserCollection userCollection = new UserCollection();
        userCollection.setUserId(String.valueOf(user.getUserId()));
        List<UserCollection> list = userCollectionService.selectUserCollectionList(userCollection);
        ArrayList<Product> orders = new ArrayList<>();
        list.forEach(item -> {
            Product product = productService.selectProductByProductId(item.getProdId());
            orders.add(product);
        });

        return success(orders);
    }


    /**
     * 查询收藏列表
     */
    @PreAuthorize("@ss.hasPermi('order:collection:list')")
    @GetMapping("/userCannelCollection")
    public AjaxResult list(UserCollection userCollection, HttpServletRequest request) {
        System.err.println(userCollection);
        List<UserCollection> list = userCollectionService.selectUserCollectionList(userCollection);
        int num = 0;
        if (list.isEmpty()) {
            num = 1;
            LoginUser user = tokenService.getLoginUser(request);
            userCollection.setUserId(String.valueOf(user.getUserId()));
            userCollectionService.insertUserCollection(userCollection);
        } else {
            num = 0;
            userCollectionService.deleteUserCollectionById(list.get(0).getId());
        }
        return success(num);
    }

    /**
     * 查询收藏列表
     */
    @PreAuthorize("@ss.hasPermi('order:collection:list')")
    @GetMapping("/isCollection")
    public AjaxResult isCollection(UserCollection userCollection) {
        List<UserCollection> list = userCollectionService.selectUserCollectionList(userCollection);
        return success(list.size());
    }

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('order:order:list')")
    @GetMapping("/mineOrderList")
    public AjaxResult list(Order order, HttpServletRequest request) {
        LoginUser user = tokenService.getLoginUser(request);
        if (order.getStatus().equals(0)) {
            order.setStatus(null);
        }
        order.setMemberId(user.getUserId());
        List<Order> list = orderService.selectOrderList(order);
        return success(list);
    }


    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('order:order:list')")
    @GetMapping("/expressDelivery")
    public AjaxResult expressDelivery(Order order) {
        List<Order> list = orderService.selectOrderList(order);
        Order order1 = list.get(0);
        return success(deliveryService.selectDeliveryByDvyId(order1.getDvyId()));
    }

    /**
     * 查询订单
     */
    @PreAuthorize("@ss.hasPermi('order:order:list')")
    @GetMapping("/mineOrder")
    public AjaxResult list(Order order) {

        List<Order> list = orderService.selectOrderList(order);
        return success(list.get(0));
    }

    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('order:order:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping("editStatus")
    public AjaxResult edit(@RequestBody Order order) {
        Order order2 = new Order();
        order2.setOrderNumber(order.getOrderNumber());
        List<Order> orders = orderService.selectOrderList(order2);
        Order order1 = orders.get(0);
        order.setOrderId(order1.getOrderId());
        return toAjax(orderService.updateOrder(order));
    }

    /**
     * 删除订单
     */
    @PreAuthorize("@ss.hasPermi('order:order:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("deleteOrder")
    public AjaxResult remove(Order order) {
        List<Order> orders = orderService.selectOrderList(order);
        Long[] orderId = new Long[orders.size()];
        for (int i = 0; i < orders.size(); i++) {
            orderId[i] = orders.get(i).getOrderId();
        }
        orderService.deleteOrderByOrderIds(orderId);
        return success(orders);
    }

    /**
     * 查询用户配送地址列表
     */
    @PreAuthorize("@ss.hasPermi('order:addr:list')")
    @GetMapping("/userAddrList")
    public AjaxResult list(UserAddr userAddr, HttpServletRequest request) {
        LoginUser user = tokenService.getLoginUser(request);
        userAddr.setUserId(String.valueOf(user.getUserId()));
        List<UserAddr> list = userAddrService.selectUserAddrList(userAddr);

        return success(list);
    }


    /**
     * 修改用户配送地址
     */
    @PreAuthorize("@ss.hasPermi('order:addr:edit')")
    @Log(title = "用户配送地址", businessType = BusinessType.UPDATE)
    @PutMapping("editCommonAddr")
    @Transactional
    public AjaxResult editCommonAddr(@RequestBody UserAddr userAddr, HttpServletRequest request) {
        LoginUser user = tokenService.getLoginUser(request);
        UserAddr userAddr1 = new UserAddr();
        userAddr1.setUserId(String.valueOf(user.getUserId()));
        List<UserAddr> userAddrs = userAddrService.selectUserAddrList(userAddr1);
        userAddrs.forEach(item -> {
            item.setCommonAddr(0L);
            UserAddr userAddr2 = new UserAddr();
            userAddr2.setAddrId(item.getAddrId());
            userAddr2.setCommonAddr(0L);
            userAddrService.updateUserAddr(userAddr2);
        });
        System.err.println(userAddr);
        return toAjax(userAddrService.updateUserAddr(userAddr));
    }

    /**
     * 获取用户配送地址详细信息
     */
    @PreAuthorize("@ss.hasPermi('order:addr:query')")
    @GetMapping(value = "getUserAddrInfo")
    public AjaxResult getInfo(Long addrId) {
        return success(userAddrService.selectUserAddrByAddrId(addrId));
    }


    /**
     * 查询地址管理列表
     */
    @PreAuthorize("@ss.hasPermi('order:area:list')")
    @GetMapping("/getAreaList")
    public AjaxResult list(Area area) {

        List<Area> list = areaService.selectAreaList(area);
        return success(list);
    }

    /**
     * 新增用户配送地址
     */
    @PreAuthorize("@ss.hasPermi('order:addr:add')")
    @Log(title = "用户配送地址", businessType = BusinessType.INSERT)
    @PostMapping("addUserAddr")
    public AjaxResult add(@RequestBody UserAddr userAddr, HttpServletRequest request) {
        LoginUser user = tokenService.getLoginUser(request);
        userAddr.setUserId(String.valueOf(user.getUserId()));
        return toAjax(userAddrService.insertUserAddr(userAddr));
    }

    /**
     * 修改用户配送地址
     */
    @PreAuthorize("@ss.hasPermi('order:addr:edit')")
    @Log(title = "用户配送地址", businessType = BusinessType.UPDATE)
    @PutMapping("editUserAddr")
    public AjaxResult edit(@RequestBody UserAddr userAddr) {
        return toAjax(userAddrService.updateUserAddr(userAddr));
    }

    /**
     * 删除用户配送地址
     */
    @PreAuthorize("@ss.hasPermi('order:addr:remove')")
    @Log(title = "用户配送地址", businessType = BusinessType.DELETE)
    @DeleteMapping("deleteUserAddr")
    public AjaxResult remove(@RequestParam Long[] addrIds) {
        return toAjax(userAddrService.deleteUserAddrByAddrIds(addrIds));
    }

    /**
     * 生成订单
     */
    @PostMapping("/confirm")
    @Operation(summary = "结算，生成订单信息", description = "传入下单所需要的参数进行下单")
    public AjaxResult confirm(@Valid @RequestBody OrderParam orderParam, HttpServletRequest request) {

        LoginUser user = tokenService.getLoginUser(request);
        // 订单的地址信息

        UserAddr userAddr = userAddrService.getUserAddrByUserId(orderParam.getAddrId(), String.valueOf(user.getUserId()));
        UserAddrDto userAddrDto = BeanUtil.copyProperties(userAddr, UserAddrDto.class);

        // 组装获取用户提交的购物车商品项
        List<ShopCartItemDto> shopCartItems = basketService.getShopCartItemsByOrderItems(orderParam.getBasketIds(), orderParam.getOrderItem(), String.valueOf(user.getUserId()));

        // 根据店铺组装购车中的商品信息，返回每个店铺中的购物车商品信息
        List<ShopCartDto> shopCarts = basketService.getShopCarts(shopCartItems);

        // 将要返回给前端的完整的订单信息
        ShopCartOrderMergerDto shopCartOrderMergerDto = new ShopCartOrderMergerDto();
        shopCartOrderMergerDto.setUserAddr(userAddrDto);

        // 所有店铺的订单信息
        List<ShopCartOrderDto> shopCartOrders = new ArrayList<>();

        double actualTotal = 0.0;
        double total = 0.0;
        int totalCount = 0;
        double orderReduce = 0.0;
        for (ShopCartDto shopCart : shopCarts) {

            // 每个店铺的订单信息
            ShopCartOrderDto shopCartOrder = new ShopCartOrderDto();
            shopCartOrder.setShopId(shopCart.getShopId());
            shopCartOrder.setShopName(shopCart.getShopName());

            List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCart.getShopCartItemDiscounts();
            // 店铺中的所有商品项信息
            List<ShopCartItemDto> shopAllShopCartItems = new ArrayList<>();
            for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartItemDiscounts) {
                List<ShopCartItemDto> discountShopCartItems = shopCartItemDiscount.getShopCartItems();
                shopAllShopCartItems.addAll(discountShopCartItems);
            }

            shopCartOrder.setShopCartItemDiscounts(shopCartItemDiscounts);

            applicationContext.publishEvent(new ConfirmOrderEvent(shopCartOrder, orderParam, shopAllShopCartItems));

            actualTotal = Arith.add(actualTotal, shopCartOrder.getActualTotal());
            total = Arith.add(total, shopCartOrder.getTotal());
            totalCount = totalCount + shopCartOrder.getTotalCount();
            orderReduce = Arith.add(orderReduce, shopCartOrder.getShopReduce());
            shopCartOrders.add(shopCartOrder);
        }
        shopCartOrderMergerDto.setActualTotal(actualTotal);
        shopCartOrderMergerDto.setTotal(total);
        shopCartOrderMergerDto.setTotalCount(totalCount);
        shopCartOrderMergerDto.setShopCartOrders(shopCartOrders);
        shopCartOrderMergerDto.setOrderReduce(orderReduce);
        shopCartOrderMergerDto = orderService.putConfirmOrderCache(String.valueOf(user.getUserId()), shopCartOrderMergerDto);
        return success(shopCartOrderMergerDto);
    }


}

